package com.goods.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.goods.pojo.Book;
import com.goods.pojo.CartItem;
import com.goods.pojo.Order;
import com.goods.pojo.OrderItem;
import com.goods.pojo.Page;
import com.goods.pojo.User;
import com.goods.service.CartItemService;
import com.goods.service.OrderService;

import cn.itcast.commons.CommonUtils;

@Controller
@RequestMapping("/OrderController")
public class OrderController {

	@Resource
	private OrderService orderServiceImpl;
	
	@Resource
	private CartItemService cartItemServiceImpl;
	
	
	/**
	 * 获取当前页码
	 * @param req
	 * @return
	 */
	private int getPc(HttpServletRequest req) {
		int pc = 1;
		String param = req.getParameter("pc");
		
		if(param != null && !param.trim().isEmpty()) {
			try {
				pc = Integer.parseInt(param);
			} catch(RuntimeException e) {}
		}
		return pc;
	}

	// 截取url，分页导航中使用它做为超链接的目标
	/*
	 * http://localhost:8080/goods/BookController/findByCategory?cid=xxx&pc=3
	 * /goods/BookController/findByCategory + cid=xxx&pc=3
	 */
	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI() + "?" + req.getQueryString();
		///goods/BookController/findByCategory?cid=5F79D0D246AD4216AC04E9C5FAB3199E++++++++++++++++++++++++++++
		System.out.println("getUrl()....................................");
		/*如果url中存在pc参数，就截取掉，否则截取。
		 * 	lastIndexOf : 从右到左，字符串出现的最后一次位置
		 *  */
		int index = url.lastIndexOf("&pc=");
		if(index != -1) {
			// 截取字符串 索引 0 - index
			url = url.substring(0, index);
		}
		return url;
	}

	// 我的订单
	@RequestMapping(value = "/myOrders")
	public String myOrders(HttpServletRequest req, HttpServletResponse resp){
		int pc = getPc(req);
		String url = getUrl(req);
		User user = (User)req.getSession().getAttribute("sessionUser");
		Page<Order> pb = orderServiceImpl.myOrders(user.getUid(), pc);
		// 给Page设置url，保存Page
		pb.setUrl(url);
		req.setAttribute("pb", pb);
		return "/jsps/order/list.jsp";
	}

	// 生成订单
	@RequestMapping(value = "/createOrder")
	public String createOrder(HttpServletRequest req, HttpServletResponse resp){
		// 获取所有购物车条目的id
		String cartItemIds = req.getParameter("cartItemIds");
		String[] cartItemIdArray = cartItemIds.split(",");
		List<CartItem> cartItemList = cartItemServiceImpl.loadCartItems(cartItemIdArray);
		// 创建Order
		Order order = new Order();
		order.setOid(CommonUtils.uuid());//设置主键
		order.setOrdertime(String.format("%tF %<tT", new Date()));//下单时间
		order.setStatus(1);//设置状态，1表示未付款
		order.setAddress(req.getParameter("address"));//设置收货地址
		User owner = (User)req.getSession().getAttribute("sessionUser");
		order.setOwner(owner);//设置订单所有者
		order.setUid(owner.getUid());
		// 精确计算
		BigDecimal total = new BigDecimal("0");
		for(CartItem cartItem : cartItemList) {
			total = total.add(new BigDecimal(cartItem.getSubtotal() + ""));
		}
		order.setTotal(total.doubleValue());//设置总计

		// 创建List<OrderItem>，一个CartItem对应一个OrderItem
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		for(CartItem cartItem : cartItemList) {
			OrderItem orderItem = new OrderItem();
			// 设置主键
			orderItem.setOrderItemId(CommonUtils.uuid());
			orderItem.setQuantity(cartItem.getQuantity());
			orderItem.setSubtotal(cartItem.getSubtotal());
			orderItem.setBook(cartItem.getBook());
			orderItem.setOrder(order);
			orderItem.setBid(cartItem.getBid());
			orderItem.setOid(order.getOid());
			orderItem.setBname(cartItem.getBook().getBname());
			orderItem.setCurrPrice(cartItem.getBook().getCurrPrice());
			orderItem.setImage_b(cartItem.getBook().getImage_b());
			orderItemList.add(orderItem);
			
		}
		order.setOrderItemList(orderItemList);

		orderServiceImpl.createOrder(order);
		// 删除购物车条目
		cartItemServiceImpl.batchDelete(cartItemIdArray);
		// 保存订单
		req.setAttribute("order", order);
		return "/jsps/order/ordersucc.jsp";
	}
	
	/**
	 * 加载订单：显示订单
	 */
	@RequestMapping(value = "/load")
	public String load(HttpServletRequest req, HttpServletResponse resp){
		String oid = req.getParameter("oid");
		Order order = orderServiceImpl.load(oid);
		req.setAttribute("order", order);
		// btn说明用户点击哪个超链接来访问本方法
		String btn = req.getParameter("btn");
		req.setAttribute("btn", btn);
		return "/jsps/order/desc.jsp";
	}
	

	// 取消订单
	@RequestMapping(value = "/cancel")
	public String cancel(HttpServletRequest req, HttpServletResponse resp){
		String oid = req.getParameter("oid");
		// 校验订单状态
		int status = orderServiceImpl.findStatus(oid);
		if(status != 1) {
			req.setAttribute("code", "error");
			req.setAttribute("msg", "状态不对，不能取消！");
			return "/jsps/msg.jsp";
		}
		// 设置状态为取消
		orderServiceImpl.updateStatus(oid, 5);
		req.setAttribute("code", "success");
		req.setAttribute("msg", "您的订单已取消，您不后悔吗！");
		return "/jsps/msg.jsp";		
	}

	// 确认收货
	@RequestMapping(value = "/confirm")
	public String confirm(HttpServletRequest req, HttpServletResponse resp){
		String oid = req.getParameter("oid");
		// 校验订单状态
		int status = orderServiceImpl.findStatus(oid);
		System.out.println(status+"======================================");
		if(status != 3) {
			req.setAttribute("code", "error");
			req.setAttribute("msg", "状态不对，不能确认收货！");
			return "/jsps/msg.jsp";
		}
		// 设置状态为交易成功
		orderServiceImpl.updateStatus(oid, 4);
		req.setAttribute("code", "success");
		req.setAttribute("msg", "恭喜，交易成功！");
		return "/jsps/msg.jsp";		
	}
	
	// 支付准备： 跳转到选择付款方式的界面
	@RequestMapping(value = "/paymentPre")
	public String paymentPre(HttpServletRequest req, HttpServletResponse resp){
		req.setAttribute("order", orderServiceImpl.load(req.getParameter("oid")));
		return "/jsps/order/pay.jsp";
	}
	
	// 支付方法
	@RequestMapping(value = "/payment")
	public String payment(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 获取订单编码
		String oid = req.getParameter("oid");
		orderServiceImpl.updateStatus(oid, 2);
		req.setAttribute("code", "success");
		req.setAttribute("msg", "恭喜，支付成功！");
		return "/jsps/msg.jsp";	

	}
}

